<!--
 * createor: zc
 * email: zc8023zs@163.com
 * create_time: 2020/3/14 13:46:24
 *-->
<template>
  <div class="app-container">
    <div class="filter-container">
        <el-button class="filter-item" style="margin-left: 10px;" v-show="permissions.p_add" type="primary" icon="el-icon-edit" @click="handleCreate">
            {{ $t('table.add') }}
        </el-button> 
    </div>
    <el-table
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column type="index" label=" " width="50" align="center" :index="table_index"></el-table-column>
      <el-table-column v-if="permissions.operation" :label="$t('table.actions')" align="center" width="370" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" v-show="permissions.p_edit" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button> 
          <el-button type="primary" size="mini" v-show="permissions.p_menu" @click="handleUpdateMenu(row)"  style="width:80px;">
            菜单授权
          </el-button> 
          <el-button type="primary" size="mini" v-show="permissions.p_perm" @click="handleUpdatePermission(row)" style="width:80px;">
            权限授权
          </el-button> 
          <el-button  size="mini" type="danger" v-if="row.init_default==0" v-show="permissions.p_del" @click="handleDelete(row)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.role_name }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="适用类别" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.user_type==0">
              <font color="green">通用</font>
            </span>
            <span v-if="scope.row.user_type==1">
              <font color="green">管理端</font>
            </span>
            <span v-if="scope.row.user_type==2">
              <font color="blue">门店端</font>
            </span> 
          </template>
      </el-table-column> 
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal='false' style="overflow-y:false" :visible.sync="dialogFormVisible" append-to-body>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" >
        <el-form-item label="角色名称" prop="role_name" show-overflow-tooltip>
          <el-input maxlength="31" v-model.trim="temp.role_name" />
        </el-form-item>  
        <el-form-item label="适用类别" prop="user_type"> 
          <el-select v-model="temp.user_type" placeholder="适用类别" value-key="id" show-overflow-toolti>
            <el-option
              v-for="item in user_types"
              :key="item.id"
              :label="item.user_type_name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>  
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog> 

    <el-dialog :visible.sync="dialogMenuTree" :close-on-click-modal='false' title="菜单授权" append-to-body>
      <el-tree ref="menuTree" :data="menuData" :props="defaultMenuProps" 
       show-checkbox  default-expand-all 
       node-key="code" >

      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogMenuTree = false">取 消</el-button>
        <el-button type="primary" @click="menuSaveClick">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="权限授权" :close-on-click-modal='false' :visible.sync="dialogPermission" append-to-body>
       <el-tree ref="permissionsTree" :data="permissionsData" :props="defaultProps" 
       show-checkbox  default-expand-all 
       node-key="permissions_code" >

      </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogPermission = false">取 消</el-button>
          <el-button type="primary" @click="permissionSaveClick">保 存</el-button>
        </span>
    </el-dialog> 
  </div>
</template>

<script>
import { fetchList, fetchObj, createObj, updateObj, getMenuTree, updateRoleMenu, deleteObj, updateRolePermission,getPermissionsTree } from '@/api/project/system/project_sys_sys_role'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { Loading } from 'element-ui';

export default {
  name: 'a_systema_sys_role',
  components: { Pagination },
  filters: {
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0, 
      permissions:{
        p_select:false,
        p_add:false,
        p_edit: false,
        p_del: false,
        p_menu: false,
        p_perm: false,
        p_menuList: false,
        p_permList: false,
        operation: false,
      },
      listQuery: {
        page: 1,
        size: 20
      }, 
      temp: {
        id: 0,
        role_name: '',
        role_menu: '',
        role_permissions: '',
        permissions_code:'',
        user_type: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      }, 
      rules: {
        role_name: [{ required: true, message: '角色名称必填', trigger: 'change' },
          { type: "string", max: 30, message: "角色名称不超过30个字", trigger: "blur"}],
          user_type: [{ required: true, message: '适用类别必填', trigger: 'change' }]
      }, 
      dialogMenuTree: false,
      menuData:null,
      mainMenu:null,
      permissionsData:null,
      defaultMenuProps: {
        children: 'children',
        label: 'menu_name'
      },
      defaultProps: {
        children: 'children',
        label: 'permissions_name'
      },
      dialogPermission: false,
      user_types:[
        // {user_type_name:'通用',id:0},
        {user_type_name:'管理端',id:1}
        // ,
        // {user_type_name:'商户端',id:2}
      ]
    }
  },
  created() {
    this.getList(),
    this.$per(result=>{ 
      this.permissions.p_select=result['*/system/sysrole/getSysRoleList']!=null;
      this.permissions.p_add=result['*/system/sysrole/addSysRole']!=null;
      this.permissions.p_edit=result['*/system/sysrole/updateSysRole']!=null;
      this.permissions.p_del=result['*/system/sysrole/deleteSysRole']!=null;

      this.permissions.p_menu=result['*/system/sysrole/menuAuthorization']!=null;
      this.permissions.p_perm=result['*/system/sysrole/permissionsAuthorization']!=null;
      this.permissions.p_menuList=result['*/system/sysmenu/getSysMenuList']!=null;
      this.permissions.p_permList=result['*/system/sysrole/getSysPermissionsList']!=null;

      if(result['*/system/sysrole/updateSysRole']!=null || result['*/system/sysrole/deleteSysRole']!=null 
            || result['*/system/sysrole/menuAuthorization']!=null || result['*/system/sysrole/permissionsAuthorization']!=null){
            this.permissions.operation=true;
      }
    })
  },
  methods: {
    table_index(index) {
      return (
        (this.listQuery.page - 1) * this.listQuery.size +
        index +
        1
      );
    },
    openFullScreen() {
        const loading = this.$loading({
          lock: true,
          text: '数据处理中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.2)'
        }); 
        setTimeout(() => {
          loading.close();
        }, 2000);
    },
    getList() { 
      fetchList(this.listQuery).then(response => {
        this.list =response.dataArray.dataList
        this.total = response.dataArray.dataCount
      })
    },
    getTree(utype,fn){ 
      this.openFullScreen();
      // getMenuTree({menu_type:1,user_type: utype}).then(response => {
      getMenuTree({user_type: utype}).then(response => {
        this.menuData = response.dataArray.dataList;
        this.mainMenu =response.ext;
        if(fn)fn();
      })
    },
    getPerTree(data){ 
      getPermissionsTree(data).then(response => {
        this.permissionsData = response.dataArray.dataList;
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    }, 
    resetTemp() {
      this.temp = {
        id: 0,
        role_name: '',
        role_menu: '',
        role_permissions: '',
        permissions_code:'',
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) { 
          this.openFullScreen();
          createObj(this.temp).then(res => { 
            this.handleFilter();
            this.dialogFormVisible = false
            if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.openFullScreen();
          const tempData = Object.assign({}, this.temp) 
          tempData.role_menu='';
          tempData.role_permissions='';
          updateObj(tempData).then(res => {
            this.handleFilter();
            this.dialogFormVisible = false
            if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
          })
        }
      })
    },
    handleDelete(row) { 
      this.$confirm('确定删除该角色？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
       this.openFullScreen();
        deleteObj(row).then(res=>{ 
        this.handleFilter();
        this.dialogFormVisible = false
        if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
      
    },
    handleUpdateMenu(row){   //打开菜单授权 
      const owner = this;
      this.getTree(row.user_type,function(){
        owner.temp = Object.assign({}, row);
        owner.dialogMenuTree = true;
        let codes = [];
        row.role_menu.split(',').forEach(item => {
          if(owner.mainMenu.indexOf("," + item + ",") < 0)
              codes.push(item);
        });
        owner.$nextTick(()=>{ 
          owner.$refs.menuTree.setCheckedKeys(codes);
        }) 
      });
    },
    handleUpdatePermission(row){//打开按钮授权
      this.getPerTree(row);
      this.temp = Object.assign({}, row);
      this.dialogPermission= true;
      this.$nextTick(()=>{  
        if(row.role_permissions!=null && row.role_permissions!="" && row.role_permissions!=undefined){
          // console.log(row.role_permissions);
          this.$refs.permissionsTree.setCheckedKeys(row.role_permissions.split(','));
        }
      }) 
    }, 
    menuSaveClick(){ //添加菜单权限
      this.openFullScreen();
      let tree = this.$refs.menuTree;

      let params = {};
      params.id=this.temp.id;
      params.role_menu=tree.getCheckedKeys().concat(tree.getHalfCheckedKeys()).join(',');
      params.role_permissions = this.temp.role_permissions;
      updateRoleMenu(this.$qs.stringify(params)).then((out)=>{
        this.dialogMenuTree= false;  
        this.handleFilter();
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
      });
    },
     perMenuTreeClick(data){
      this.permissions = [];  
      var array = this.temp.role_permissions.split(',');
      for(var i=0;i<data.permissions.length;i++){
        for(var ii=0;ii<array.length;ii++){
          if(data.permissions[i].value==array[ii]){
            data.permissions[i]['checked']=true;
          }
        }
      } 
      this.permissions = data.permissions;
    },
    permissionSaveClick(data){//添加按钮权限
      this.openFullScreen();
      var permissions = this.$refs.permissionsTree.getCheckedKeys();
      for(var i=permissions.length;i>0;i--){
        if(permissions[i-1]==''){
          permissions.splice(i-1,1);
        }
      } 
      let params = {};
      params.id=this.temp.id;
      params.role_permissions=permissions.join(',');
      params.role_menu = this.temp.role_menu;
      console.log(this.$qs.stringify(params));
      updateRolePermission(this.$qs.stringify(params)).then((out)=>{
        this.dialogPermission= false;  
        this.handleFilter();
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
      });
    }
  }
}
</script>
